package com.giscloud.commons.utils;

import com.giscloud.commons.codec.DigestsUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * @Author:giscloud
 * @Description:
 * @Date: 22:44 2018/3/21
 * @Modified By:
 */
public class PasswordUtils {
    protected final static Logger log = LoggerFactory.getLogger(PasswordUtils.class);

    public static void main(String[] args) throws Exception{
        String md5Pass = DigestsUtils.MD5Encode(DigestsUtils.MD5Encode("123456".toUpperCase()).toUpperCase()).toLowerCase();

        System.out.println("getSalt:"+getSalt(16));
        System.out.println(generatePassword(md5Pass,getSalt(16)));
        String password = generatePassword(md5Pass,getSalt(16));
        System.out.println(verify(md5Pass, password));

        System.out.println(md5Hex("testtest",null));
    }
    /*
    * 生成含有随机盐的密码
    */
    public static String generatePassword(String password,String salt){
        password = md5Hex(password + salt,null);
        char[] cs = new char[48];
        for (int i = 0; i < 48; i += 3) {
            cs[i] = password.charAt(i / 3 * 2);
            char c = salt.charAt(i / 3);
            cs[i + 1] = c;
            cs[i + 2] = password.charAt(i / 3 * 2 + 1);
        }
        return new String(cs);
    }
    /*
    * 生成随机盐（一般大于等于16位）
    */
    public static String getSalt(int len){
        Random r = new Random();
        StringBuilder sb = new StringBuilder(len);
        sb.append(r.nextInt(99999999)).append(r.nextInt(99999999));
        int length = sb.length();
        if (length < len) {
            for (int i = 0; i < len - length; i++) {
                sb.append("0");
            }
        }
        String salt = sb.toString();
        return salt;
    }
    /**
     * 校验密码是否正确
     */
    public static boolean verify(String password, String md5) {
        char[] cs1 = new char[32];
        char[] cs2 = new char[16];
        for (int i = 0; i < 48; i += 3) {
            cs1[i / 3 * 2] = md5.charAt(i);
            cs1[i / 3 * 2 + 1] = md5.charAt(i + 2);
            cs2[i / 3] = md5.charAt(i + 1);
        }
        String salt = new String(cs2);
        return md5Hex(password + salt,null).equals(new String(cs1));
    }

    /*
     * 获取十六进制字符串形式的MD5
     */
    public static String md5Hex(String src,String charSet) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            if (charSet == null) {
                messageDigest.update(src.getBytes());
            } else {
                messageDigest.update(src.getBytes(charSet));
            }
            byte[] byteArray = messageDigest.digest();
            StringBuffer md5StrBuff = new StringBuffer();
            for (int i = 0; i < byteArray.length; i++) {
                if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                    md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
                }
                else {
                    md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
                }
            }
            return md5StrBuff.toString();
            //byte[] bs = messageDigest.digest(src.getBytes());
            //return new String(new Hex().encode(bs));
        } catch (NoSuchAlgorithmException e) {
            log.error("md5 error:" + e.getMessage(), e);
            return null;
        } catch (UnsupportedEncodingException e) {
            log.error("md5 error:" + e.getMessage(), e);
            return null;
        }
    }
}
